﻿using System;
using CSEngine;

namespace Server
{
    public sealed class Expression
    {
        public enum ExprType { COMMAND, MOVE, COMMENT, INVALID }
        private object val;
        private ExprType type;

        public Expression()
        {
            type = ExprType.INVALID;
        }

        private Expression(ExprType expr_type, object value)
        {
            val = value;
            type = expr_type;
        }

        public ExprType Type
        {
            get { return type; }
        }

        public object Value
        {
            get { return val; }
        }

        /// <summary>
        /// Attempt to parse an Expression from a given string
        /// </summary>
        /// <param name="s">The string to parse</param>
        /// <exception cref="System.ArgumentException">Thrown if the given String
        /// could not be parsed into an Expression</exception>
        public static Expression Parse(String s)
        {
            String str = s.Trim();
            String[] words = s.Split(' ');
            Command com;
            Move mov;
            if (s[0] == ';')
                return new Expression(ExprType.COMMENT, s.Substring(1));
            else if (Command.TryParse(words[0], out com))
                return new Expression(ExprType.COMMAND, com);
            else if (Move.TryParse(words[0], out mov))
                return new Expression(ExprType.MOVE, mov);
            else
                throw new ArgumentException();
        }

        public static bool TryParse(String s, out Expression expr)
        {
            try
            {
                expr = Parse(s);
                return true;
            }
            catch (ArgumentException)
            {
                expr = new Expression();
                return false;
            }
        }
    }
}
